<?php
/**
 * 首页低层处理类
 * 提供数据库处理和低层数据的输出
 * 
 * @copyright Copyright (c) 2008 sdmblog (http://www.sdmblog.cn)
 * @author sdomain(sdomain@live.cn)
 * @version index.model.php Sat May 17 16:57:10 CST 2008 php $
 */
class model_index {
	var $rowCount = 0;
	var $queryCount = 0;
	var $pageCount = 0;
	var $sql = 0;
	/**
	 * 取得贴子列表
	 * 
	 * @param $page int 当前第几页(默认为1)
	 * @param $condition mix 符加条件，如日期：date
	 * @param $where mix 符加条件的内容，如日期中的2008-01
	 * @param $pagesize int 每页记录数（默认为10，从数据库的配置表内读取）
	 * @return array 用与显示记录列表的数组,如果没有数据则返回0
	 */
	function getArticleList($page = 1,$condition='',$content='',$pagesize = 20) {
		global $db,$tablepre,$cfg_normalperpage,$cfg_listperpage,$vmodel,$noLoginRight;
		global $secret_id,$datafilecachepath,$cachefile;
		$cfg_normalperpage = empty($cfg_normalperpage)?$pagesize:intval($cfg_normalperpage);
		$cfg_listperpage = empty($cfg_listperpage)?$pagesize:intval($cfg_listperpage);
		$pagesize = ($vmodel=='normal')?$cfg_normalperpage:$cfg_listperpage;
		//处理当前用户阅读权限问题
		$userInfo = islogin();
		$userRight = $userInfo==0?$noLoginRight:$userInfo[4];
		$articleType = substr($userRight,0,1);
		$arrcond = explode(',',$condition);
		$arrcont = explode(',',$content);
		if (!$arrcond || !$arrcont) {
			$where  = "";
		}else {
			if (count($arrcond)!=count($arrcont)) {
				//如果查出来的参数不配对，则无法进行查询
				throw new Exception('参数不配对，无法进行查询');
			}
			foreach ($arrcond as $keycond=>$contcond){
				if (!empty($where)) {
					$where .= ' and ';
				}
				switch ($contcond){
					case 'category':
						if (!is_numeric($arrcont[$keycond])) {
							$arrcont[$keycond] = 0;
						}
						if ((int)$arrcont[$keycond]>0) {
							$where .= " category = ".$arrcont[$keycond];
						}
						break;
					case 'date':
						$arrarea=getdatearea($arrcont[$keycond]);
						if (is_array($arrarea)){
							$where .= " adddate >= ".$arrarea['start']." and adddate <=".$arrarea['stop'];
						}
						break;
				}
			}
			
		}
		
		//$where = empty($where)?'':' where '.$where;
		//$str = empty($where)?'':' where ';
		$where = empty($where)?'':' where '.$where;
		$sql = "select count(*) from ".$tablepre."articles ".$where;
		$this->sql = $sql;
		$res = $db->query($sql);
		$arr = $db->db_fetch_array($res);
		$this->rowCount = $arr[0];
		
		$pageCount=ceil($this->rowCount/$pagesize);
		$this->pageCount = $pageCount;
		$page = $page>$pageCount?$pageCount:$page;
		$page = $page<0?0:$page;
		$offset = $page>0?($page - 1) * $pagesize:0;
		
		
		$where=$where==""?" where c.id=a.category ":$where." and c.id=a.category";
		$sql = "select a.id,a.title,a.content,a.adddate,a.author,a.submitip,a.comments,a.views,c.name as categoryname,c.id as cid from ".$tablepre.
		"articles a,".$tablepre."categories c ".$where." order by adddate desc limit ".$offset.",".$pagesize;
		$this->sql = $sql;
		
		
		$datafilename = md5($sql.$secret_id).'.php';
		if (!file_exists(ROOT_PATH.$datafilecachepath.$cachefile)||!file_exists(ROOT_PATH.$datafilecachepath.$datafilename)) {
			//从数据库内取文件,并生成缓存数据文件
			//格式就是一个数组的定义在输出HTML的方法里,直接循环此数组
			$res = $db->query($sql);
			$this->queryCount = $db->numRows;
			while ($array = $db->db_fetch_array($res)) {
				//$array['content'] = getHtmlContent($array['content']);
				$article[] = $array['id'];
			}
			$strarticleid = implode(',',$article);
			$datafilecontent = '<?
/**
 * 缓存数据文件格式,则程序自动生成,输入页面的程序包函此文件,再去读文件
 * id 为文章编号author为文章
 */
$che_article = array('.$strarticleid.');
			?>';
			$cachefilecontent = '/*
			缓存文件标志-有此文件时读缓存，无缓存
			*/';
			$error = write_file($datafilecontent,$datafilecachepath,$datafilename);
			if (!$error) {
				$error = write_file($cachefilecontent,$datafilecachepath,$cachefile);
				if ($error) {
					throw new Exception('写文章数据缓存文件失败，错误代码：'.$error);
				}
			}else {
				throw new Exception('写缓存标志文件失败，错误代码：'.$error);
			}
			return array('readcache'=>true,'cachename'=>$datafilename);
		}else {
			//可以从缓存文件内取
			return array('readcache'=>true,'cachename'=>$datafilename);
		}
	}
	/**
	 * 根据文章数组。输出页面上显示的HTML代码
	 *
	 * @param array $articles 文章数组
	 * @return string 在页面上显示的HTML代码
	 */
	function getArticleHtml($data,$mode)
	{
		global $lang,$virdir,$secret_id,$datafilecachepath,$htmlfilecachepath;
		$datafilename = $data['cachename'];
		$readcache = $data['readcache'];
		if ($readcache) {
			include_once(ROOT_PATH.$datafilecachepath.$datafilename);//包函文件
			foreach ($che_article as $articleid) {
				//$che_article是前面包函的缓存文件内定义的
				//生成文章文件名文章配置文件名就是$afilename_conf 列表就是:$afilename_list 详细页就是$afilename
				$afilename = $htmlfilecachepath.md5($articleid.$secret_id);
				if (!file_exists($afilename.'_conf')||!file_exists($afilename.'_list')||!file_exists($afilename)) {
					//如果文章文件没有,则生成一个,需要进行数据库操作了
					//生成的时候放到一个函数内操作-返回生成的HTML代码,就不用再去读文件了
					$strHTML.=makearticlecache($articleid); 
					continue;
				}
				//如果文章缓存文件都有,则读缓存文件
				//定义一个公共函数可以读配置文件内的内容,还有写
				$author = readconfig($afilename.'_conf','author');
				
			}
		}else {
			//无缓存
		}
		
		
		if ($mode=='normal') {
		foreach ($articles as $article){
				$strHTML .= '
							<div class="textbox" >
  							<div class="textbox-title">
							<h4>
	  						<a href="/'.$virdir.'article.php/id/'.$article[id].'">'.$article[title].'</a>
    						</h4>
    						<div class="textbox-label">[ '.date("Y-m-d H:i:s",$article[adddate]).' | '.$lang[AUTHOR].': <a href="/'.$virdir.'user.php/act/view/uname/'.$article[author].'">'.$article[author].'</a> ]</div>
  							</div>
  							<div class="textbox-content">'.$article[content].'</div>
  							<div class="textbox-bottom">
    						<a href="#">'.$lang[CATEGORY].': '.$article[categoryname].'</a> |
    						<a href="/'.$virdir.'article.asp/id/40#commentbox">'.$lang[COMMENTS].': '.$article[comments].'</a> | '.$lang[VIEWS].': '.$article[views].'
  							</div>
							</div>';
}
		}else {
			foreach ($articles as $article){
				//$article['content'] =
				$strHTML .= '
							<tr>
  							<td class="listbox-entry">
    						<a href="/'.$virdir.'index.php/C/'.$article['cid'].'">['.$article['categoryname'].']</a>
    						<a href="/'.$virdir.'article.php/id/'.$article['id'].'">'.$article['title'].'</a>
							</td>
  							<td class="listbox-entry" style="word-break: normal;">
    						<a href="/'.$virdir.'user.php/act/view/uname/'.$article['author'].'" title="'.$lang['AUTHOR'].'">'.$article['author'].'</a>
  							</td>
  							<td class="listbox-entry" width="70">2008-03-25</td>
 							<td class="listbox-entry" width="100"><a href="article.php?id=43#commentbox" title="'.$lang['COMMENTS'].'">2</a> | 0 | '.$article['views'].'</td>
							</tr>
							';
			}
			$strHTML = '<div class="listbox">
						<div class="listbox-table">
						<table cellpadding="2" cellspacing="2" width="100%">
						'.$strHTML.'
						</table>
						</div>
						</div>
						';
		}
		return $strHTML;
	}
	/**
	 * 分类列表数据
	 *
	 * @return unknown
	 */
	
	function getCategoryList(){
		global $db,$tablepre;
		$sql = 'select id,name,articlenum from '.$tablepre.'categories where hidden=0';
		$db->query($sql);
		$this->rowCount = $db->numRows;
		$this->queryCount = $this->rowCount;
		while ($array = $db->db_fetch_array()) {
			$arrcategory[] = $array;
		}
		return $arrcategory;
	}
	/**
	 * 分类列表的HTML内容
	 *
	 * @param unknown_type $categories
	 * @return unknown
	 */
	function getCategoryHtml($categories)
	{
		global $lang;
		if (!is_array($categories)) {
			$strHTML = '<li><a href="#" onclick="getArticleList(0,\'\',\'\');"><b>首页</b></a></li>
						<li>'.$lang['NOCATEGORY'].'</li>';
		}else {
			foreach ($categories as $category) {
				$strHTML .= '
							<li><a href="#" onclick="getArticleList(0,\'category\','.$category['id'].');">'.$category['name'].'['.$category['articlenum'].']</a></li>';
			}
			$strHTML = '<li><a href="#" onclick="getArticleList(0);"><b>首页</b></a></li>'.$strHTML;
		}
		$strHTML = '<ul>
					'.$strHTML.'
					</ul>';
		return $strHTML;
	}
	/**
	 * 最新的文章
	 *
	 * @return unknown
	 */
	function getRecentArticles()
	{
		global $db,$tablepre,$cfg_newblognum;
		$cfg_newblognum = empty($cfg_newblognum)?10:intval($cfg_newblognum);
		$sql = 'select id,title from '.$tablepre.'articles order by adddate desc limit 0,'.$cfg_newblognum;
		$res = $db->query($sql);
		while ($array = $db->db_fetch_array($res)) {
			$arr[] = $array;
		}
		return $arr;
	}
	/**
	 * 最新文章HTML内容
	 *
	 * @param unknown_type $arrRecent
	 * @return unknown
	 */
	function getRecentHtml($arrRecent)
	{
		global $lang,$virdir;
		if (!is_array($arrRecent)){
			$strHTML = '<ul>
						<li>'.$lang['NO_ANY_ARTICLES'].'</li>
  						</ul>';
		}else {
			foreach ($arrRecent as $array){
				$strHTML .= '
							<li><a href="/'.$virdir.'article.php/id/'.$array['id'].'">'.$array['title'].'</a></li>
							';
			}
			$strHTML = '<ul>
						'.$strHTML.'
						</ul>';
		}
		return $strHTML;
	}
	/**
	 * 文章回复数据
	 *
	 * @return unknown
	 */
	function getComment()
	{
		global $db,$tablepre,$cfg_newcomment;
		$cfg_newcomment = empty($cfg_newcomment)?10:intval($cfg_newcomment);
		$sql = 'select r.id as cid,a.id as id,r.content as content,a.title as title,u.username as username from '.$tablepre.'revert r ,'.$tablepre.'articles a,'.$tablepre.'users u where a.id = r.articleid and u.id = r.userid order by r.adddate desc limit 0,'.$cfg_newcomment;
		$res = $db->query($sql);
		while ($array = $db->db_fetch_array($res)) {
			$arr[] = $array;
		}
		return $arr;
	}
	/**
	 * 获取回复的HTML内容
	 *
	 * @param unknown_type $arrComment
	 * @return unknown
	 */
	function getCommentHtml($arrComment)
	{
		global $lang,$virdir;
		if (!is_array($arrComment)){
			$strHTML = '<ul>
						<li>'.$lang['NO_ANY_COMMENT'].'</li>
  						</ul>';
		}else {
			foreach ($arrComment as $array){
				$strHTML .= '
							<li><a href="/'.$virdir.'article.php/id/'.$array['id'].'#comment'.$array['cid'].'" title = "'.$array['content'].'">'.cutStr($array['content'],20,true).'</a></li>
							';
			}
			$strHTML = '<ul>
						'.$strHTML.'
						</ul>';
		}
		return $strHTML;
	}
	/**
	 * 通过年月，得到当月的每天的文章数
	 *
	 * @param int $year 年
	 * @param int $month 月
	 * @return array 以天为下标的文章列表数组
	 */
	function getMonthArticleList($year,$month)
	{
		global $db,$tablepre;
		$start = strtotime($year.'-'.$month.'-01'.' 00:00:00');
		$stop = strtotime($year.'-'.$month.'-'.date('t',strtotime($year.'-'.$month)).' 23:59:59');
		$sql = 'select title,adddate from '.$tablepre.'articles where adddate >='.$start.' and adddate <='.$stop.' order by adddate';
		$res = $db->query($sql);
		while ($arr=$db->db_fetch_array($res)) {
			$day = date('d',$arr['adddate']);
			$array[$day][] = $arr;
		}
		return $array;
	}
	/**
	 * 通过一月的文章列表，得到用与显示日历的HTML代码
	 *
	 * @param int $year 年份
	 * @param int $month 月份
	 * @param array $arrdata 文章列表
	 * @return string 显示日历的HTML代码
	 */
	function getCalendarHtml($year,$month,$arrdata)
	{
		$date = strtotime($year.'-'.$month.'-'.'1');
		//一号星期几
		//$dayoneweek = date('w',$date);
		$i = 0;
		$day = 1;//日，从一开始
		$allday = date('t',strtotime($year.'-'.$month));//总天数
		//得出此月所有日的文章情况，如果有文章就把对应天内容加上文章
		for ($i=1;$i<=$allday;$i++){
			if (is_array($arrdata[$i])) {
				foreach ($arrdata[$i] as $daydata){
					$strtitle = empty($strtitle)?'':$strtitle."\r\n";
					$strtitle =$strtitle.'-'.$daydata['title'];
				}
				$arrdaystr[$i]= '<a href ="#" class="calendar" onclick="getArticleList(1,\'date\',\''.$year.'-'.$month.'-'.$i.'\')" title="'.$strtitle.'">'.$i.'</a>';
				$strtitle ='';
			}else {
				//否则数据就是当天的日数
				$arrdaystr[$i] = $i;
			}
		}
		while ($day <= $allday) {
			for ($i=0;$i<7;$i++){
				$dayweek = date('w',strtotime($year.'-'.$month.'-'.$day));
				$nowyear = date('Y');
				$nowmonth = date('m');
				$nowday = date('d');
				if ((int)$nowyear==(int)$year &&(int)$nowmonth==(int)$month && (int)$nowday==(int)$day ) {
					$isnowdate = true;
				}else {
					$isnowdate = false;
				}
				
				if ($i==$dayweek && $day<=$allday) {
					if ($isnowdate) {
						$strtemp .='<td class="calendar-today">'.$arrdaystr[$day].'</td>'."\r\n";
					}else{
						if ($i==0) {
							$strtemp .='<td class="calendar-sunday">'.$arrdaystr[$day].'</td>'."\r\n";
						}elseif ($i==6){
							$strtemp .='<td class="calendar-saturday">'.$arrdaystr[$day].'</td>'."\r\n";
						}else {
							$strtemp .='<td class="calendar-day">'.$arrdaystr[$day].'</td>'."\r\n";
						}
					}
					$day++;
				}else {
					$strtemp .='<td class="calendar-day-blank"></td>'."\r\n";
				}
			}
			$strweek .='<tr>'."\r\n".$strtemp.'<tr>'."\r\n";
			$strtemp ='';
		}
		$preyearstr = ($year - 1).','.$month;
		$thisyearstr = $year.','.$month;
		$nextyearstr = ($year + 1).','.$month;
		$premonthstr = ($month==1?($year - 1):$year).','.($month==1?'12':($month -1));
		$thismonthstr = $thisyearstr;
		$nextmonthstr = ($month==12?($year + 1):$year).','.($month==12?'1':($month +1));
		$strdatestr = $year.'-'.$month;
		$thismonthex = date('M',strtotime($strdatestr));
		$strHTML ='
					<table cellspacing="1" width="100%" id="calendar">
					<tr>
					<td colspan="7" class="calendar-top">
					
						<a href="#" onclick="getCalendar('.$preyearstr.');">&laquo;</a>
						<a href="#" onclick="getArticleList(1,\'date\',\''.$strdatestr.'\');"><span class="calendar-year">'.$year.'</span></a>
						<a href="#" onclick="getCalendar('.$nextyearstr.');">&raquo;</a>
						&nbsp;&nbsp;
						<a href="#" onclick="getCalendar('.$premonthstr.');">&laquo;</a>
						<a href="#" onclick="getArticleList(1,\'date\',\''.$strdatestr.'\');"><span class="calendar-month">'.$thismonthex.'</span></a>
						<a href="#" onclick="getCalendar('.$nextmonthstr.');">&raquo;</a>
					
					</td>
					
					</tr>
					<tr class="calendar-weekdays">
						<td class="calendar-weekday-cell">Su</td>
						<td class="calendar-weekday-cell">Mo</td>
						<td class="calendar-weekday-cell">Tu</td>
						<td class="calendar-weekday-cell">We</td>
						<td class="calendar-weekday-cell">Th</td>
						<td class="calendar-weekday-cell">Fr</td>
						<td class="calendar-weekday-cell">Sa</td>
					</tr>
					'.$strweek.'
					</table>
					';
		return $strHTML;
	}
	function getStatsData()
	{
		global $db,$tablepre;
		$arrResult = array();
		//文章数
		$sql = 'select count(id) from '.$tablepre.'articles';
		$res = $db->db_query_one($sql);
		
		if ($res !=0) {
			throw new Exception($res);
		}
		$arrResult['articleCount'] = $db->result[0];
		//回复数
		$sql = 'select count(id) from '.$tablepre.'revert';
		$res = $db->db_query_one($sql);
		if ($res !=0) {
			throw new Exception($res);
		}
		$arrResult['commentCount'] = $db->result[0];
		//注册用户
		$sql = 'select count(id) from '.$tablepre.'users';
		$res = $db->db_query_one($sql);
		if ($res !=0) {
			throw new Exception($res);
		}
		$arrResult['userCount'] = $db->result[0];
		//访问量
		$arrResult['visitCount'] = 0;
		//在线用户
		$arrResult['onlineCount'] = 0;
		return $arrResult;
	}
	function getStatsHtml($statsData)
	{
		global $lang,$virdir;
		$strHTML = '
					<li>'.$lang['ARTICLES'].': '.$statsData['articleCount'].'<br /></li>
					<li><a href="/'.$virdir.'comment.asp">'.$lang['COMMENTS'].': '.$statsData['commentCount'].'</a></li>
					<li><a href="/'.$virdir.'trackback.asp?act=list">'.$lang['TRACKBACK'].': NULL</a></li>
					<li><a href="/'.$virdir.'user.asp">'.$lang['REGUSERS'].':  '.$statsData['userCount'].'</a></li>
					<li><a href="/'.$virdir.'stats.asp" target="_blank">'.$lang['VISITORS'].':  '.$statsData['visitCount'].'</a></li>
					<li>'.$lang['ONLINEUSERS'].': '.$statsData['onlineCount'].' </li>
					';
		return $strHTML;
	}
	
}
/*
$index = new model_index();
var_dump($index->getArticleList());
*/
?>